# V2.1.1
import logging
import sys

from datetime import datetime
from concurrent_log_handler import ConcurrentRotatingFileHandler
from pathlib import Path


PLATFORM = sys.platform
if PLATFORM == 'win32':
    if sys.getwindowsversion().major == 6:
        PLATFORM += ' win7'
    elif sys.getwindowsversion().major == 10:
        PLATFORM += ' win11'
else:
    pass
SCRIPTP = Path(__file__).parent.parent
HOMEP = Path(sys.executable).parent
if sys.argv[0].endswith('.py'):
    DEBUG = True
    HOMEP = SCRIPTP
else:
    DEBUG = False
    if str(SCRIPTP.parent.name) == '_internal':
        HOMEP = SCRIPTP.parent
VERSION = 'debug' if DEBUG else str(HOMEP.name)
if DEBUG:
    print(f'版本: {VERSION}')
    print(f'脚本目录: {SCRIPTP}')
    print(f'工作目录: {HOMEP}')
    print(f'平台: {PLATFORM}')


# 检查logs目录是否存在，存在清空
logs_dir = HOMEP.joinpath('logs')
SAVE_LOG = False
if SAVE_LOG:
    # 日志文件路径
    LOG_DIR = str(logs_dir)
    if DEBUG:
        if logs_dir.exists():
            try:
                for file in logs_dir.iterdir():
                    file.unlink()
            except Exception as e:
                print(f'清空日志目录失败: {e}')
        else:
            logs_dir.mkdir(parents=True)
    else:
        if logs_dir.exists() and len(list(logs_dir.iterdir())) > 30:
            try:
                for file in logs_dir.iterdir():
                    file.unlink()
            except Exception as e:
                print(f'清空日志目录失败: {e}')
        elif not logs_dir.exists():
            logs_dir.mkdir(parents=True)
LEVEL = logging.DEBUG

# 配置日志记录器
logger = logging.getLogger('log')
logger.setLevel(LEVEL)

# 创建控制台处理器
console_handler = logging.StreamHandler()
console_handler.setLevel(LEVEL)
console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)

if SAVE_LOG:
    try:
        # log_file = str(logs_dir.joinpath(f'{datetime.now().strftime("%Y-%m-%d")}_{len(list(logs_dir.iterdir()))}.log'))
        log_file = str(logs_dir.joinpath(f'{datetime.now().strftime("%Y-%m-%d")}.log'))
        file_handler = ConcurrentRotatingFileHandler(log_file, maxBytes=1024*1024, backupCount=31, encoding='utf-8')
        # file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(LEVEL)
        file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s')
        file_handler.setFormatter(file_formatter)
        logger.addHandler(file_handler)
    except Exception as e:
        print(str(e))


# 导出日志函数
def debug(msg):
    try:
        logger.debug(msg)
    except Exception:
        pass


def info(msg):
    try:
        logger.info(msg)
    except Exception:
        pass


def warning(msg):
    try:
        logger.warning(msg)
    except Exception:
        pass


def error(msg):
    try:
        logger.error(msg)
    except Exception:
        pass


def critical(msg):
    try:
        logger.critical(msg)
    except Exception:
        pass
